upload_data = {};

$(function(){
    var leftImage = $('#left-source-image'),
        preview = canvasIns($('#header-img-editor')[0]),
        shader = shaderIns('#header-shade',preview),
        localImage = localImageIns('#localimage',preview,shader),
		rslpanel = $('#right-chip-face');

    $('#search-btn').click(function(e){
        if(!upload_data.image)
            return alert("还没有指定图片!");
        var form = new FormData()

		// if(rslpanel.children().length != 0)
		// 	rslpanel.empty();
		// console.log(rslpanel.children())

        form.append('image',upload_data.image);
        form.append('option',upload_data.option);

        $.ajax({
            type: 'POST',
            url: '/upload/',
            dataType: 'json',
            processData: false,
            contentType: false,
            data: form, 
            success: function(data,textStatus){
				
                if(typeof(data) == 'object'){
					if(data['type'] == 'None'){
						var msg = document.createElement('p');
						msg.innerText = data['msg'];
						$(msg).appendTo(rslpanel).fadeIn('slow','linear');
					}
					if(data['type'] == 'test'){
						var img = new Image();
						img.src = data['src'];
						img.onload = function(e){
							$(img).css('width','100%').css('height','100%').appendTo(rslpanel);
						};
						img.onerror = function(e){
								alert("无法加载图片...");
						};
						
					}
					if(data['type'] == 'identify'){
						for(var i in data['src']){
							var img = document.createElement('img');
							img.src = data['src'][i];
							img.onload = function(e){
								$(img).appendTo(rslpanel);
							};
							img.onerror = function(e){
								alert("无法加载图片...");
							};
						}
					}
					// $('#right-chip-face')
				}

            },
            error: function(xhr,textStatus){
                alert('图片传输出现错误！');
                // console.log('error');
            }
        });
        // ajax(
        //     url='/upload/',
        //     method='POST',
        //     param = form,
        //     success = function(e){

        //     },
        //     error = function(e){
        //         console.log(e);
        //     }
        // )
    });
});


function test(){
    var image = upload_data.image,
        reader = new FileReader();
    // reader.onload = function(e){
    //     document.body.style.background = "url("+e.currentTarget.result+") no-repeat";
    // };
    // reader.readAsBinaryString(image);
    document.body.style.background = "url("+image+") no-repeat";
}


/**
 * 序列化canvas
 * @param {HTMLElement} canvas canvas元素实例
 */
function canvasIns(canvas) {
	var ctx = canvas.getContext('2d'),
        parent = canvas.parentElement;

    canvas.setAttribute('width',parent.offsetWidth+'px');
    canvas.setAttribute('height',parent.offsetHeight+'px');
	/**
	 * 在canvas中显示指定图片
	 * @param {Image} img 图片实例对象
	 * @param {Function} callback 回调函数，返回参数canvas,context实例
	 */
	canvas.showimg = function (img, callback) {
		var self = this;
		ctx.drawImage(img, 0, 0, parseFloat(getComputedStyle(self)['width']), parseFloat(getComputedStyle(self)['height']));
		self.parentElement.className = [self.parentElement.className, 'header-img-editor-area-alive'].join('\u0020');

        if(!!callback)
            return callback(canvas);
	}

	canvas.getHeaderImage = function (x, y, width, height) {
		var imagedata = ctx.getImageData(x, y, width, height),
			subcan = document.createElement('canvas'),
			subctx = subcan.getContext('2d');
		subcan.width = imagedata.width;
		subcan.height = imagedata.height;
		subctx.putImageData(imagedata, 0, 0);
		return subcan.toDataURL();
	}

	/**
	 * 调节canvas大小函数
	 * @param {Number} width 目标宽度
	 * @param {Number} height 目标高度
	 */
	canvas.resize = function (width, height) {
		var image = new Image(),
			self = this;
		image.src = self.toDataURL();
		self.width = width;
		self.height = height;
		ctx.drawImage(image, 0, 0, width, height);
	}
	return canvas;
}


function shaderIns(shadeId, canvas) {
	var shader = querySelector(shadeId);

	shader.addEventListener('mousemove', function (e) {
		var self = this, // self == shader self
			pos = self.getBoundingClientRect();
		/**
		 * 调成遮罩层大小函数
		 * @param {Event} e 鼠标左键点击事件
		 */
		function resize(e) {
			var oldX, oldY;
			oldX = e.clientX;
			oldY = e.clientY;
			self.onmousemove = function (e) {
				var deltaX = e.clientX - oldX,
					deltaY = e.clientY - oldY;
				oldX = e.clientX;
				oldY = e.clientY;
				self.style.width = parseFloat(getComputedStyle(self)['width']) + deltaX + 'px';
				self.style.height = parseFloat(getComputedStyle(self)['height']) + deltaY + 'px';

				var header = canvas.getHeaderImage(self.offsetLeft, self.offsetTop, self.offsetWidth, self.offsetHeight);
                extractImage(header);
			}
		}
		/**
		 * 移动遮罩层函数
		 * @param {Event} e 鼠标左键点击事件
		 */
		function move(e) {
			var oldX = e.clientX,
				oldY = e.clientY,
                header;
			self.onmousemove = function (e) {
				var deltaX = e.clientX - oldX,
					deltaY = e.clientY - oldY,
					header;
				oldX = e.clientX;
				oldY = e.clientY;
				if (self.offsetLeft + deltaX >= 0 && self.offsetLeft + self.clientWidth + deltaX <= canvas.clientWidth)
					self.style.left = parseFloat(getComputedStyle(self)['left']) + deltaX + 'px';
				if (self.offsetTop + deltaY >= 0 && self.offsetTop + self.clientHeight + deltaY <= canvas.clientHeight)
					self.style.top = parseFloat(getComputedStyle(self)['top']) + deltaY + 'px';

				var header = canvas.getHeaderImage(self.offsetLeft, self.offsetTop, self.offsetWidth, self.offsetHeight);
                extractImage(header);
			}
		}
		/**
		 * 元素绑定元素清理函数
		 * @param {Event} e 
		 */
		function destroy(e) {
			self.onmouseup =
				self.onmouseout =
				self.onmousemove =
				canvas.onmousemove =
				canvas.onmouseout = undefined;
		}

		if (e.clientX - pos.left < pos.width - getOnevw() && e.clientY - pos.top < pos.height - getOnevh()) {
			self.style.cursor = 'move';
			self.onmousedown = move;
			self.onmouseup = self.onmouseout = canvas.onmouseout = destroy;
		} else {
			self.style.cursor = 'se-resize';
			self.onmousedown = resize;
			self.onmouseup = self.onmouseout = destroy;
		}
	}, false);
    shader.close = function(){
        var self = this;
        self.removeAttribute('class');
        self.style.display = 'none';
    }
    shader.show = function(){
        var self = this;
        shader.setAttribute('class', 'header-shade-alive');
        self.removeAttribute('style');
    }
	return shader;
}


/**
 * 快速DOM元素获取,调用方法类似jquery
 * @param {String} eleid DOM元素的辨别属性字段
 * @return {HTMLElement} 获取到的DOM元素
 */
function querySelector(eleid){
	switch(eleid.substr(0,1)){
		case ".":
			return document.getElementsByClassName(eleid.substr(1));
		case "#":
			return document.getElementById(eleid.substr(1));
		case "[":
			return document.querySelector(eleid);
		default:
			return document.getElementsByTagName(eleid) || document.getElementsByName(eleid);
	}
}


/**
 * 本地图片上传处理函数
 * @param {String} localimageid 本地图片输入控件id
 * @param {HTMLElement} parent uploadHeader实例
 * @return {HTMLElement} localimage 本地输入控件实例
 */
function localImageIns(localimageid, canvas,shader) {
	var localimage = querySelector(localimageid),
        option = querySelector('#search-type');
    upload_data.option = option.value;
    option.addEventListener('change',function(e){
            var type = option.value;
            if(type == 'identify'){
                shader.show();
                if(!!upload_data.isimg){
                    var header = canvas.getHeaderImage(shader.offsetLeft,shader.offsetTop, shader.offsetWidth, shader.offsetHeight);
                    extractImage(header);
                }
                upload_data.option = type;
            }
            else{
                shader.close();
                if(!!upload_data.isimg)
                    extractImage(upload_data.src)
                upload_data.option = type;
            }
        });
    
	localimage.addEventListener('change', function (e) {
		var imgfile = e.target.files[0],
			reader = new FileReader(),
			img = new Image(),
            header;
            
		if(!imgfile) return;
        upload_data.image_type = imgfile.type
		reader.onload = function (e) {
			img.src = e.currentTarget.result;
			img.onload = function (e) {
                upload_data.isimg = true;
                upload_data.src = img.src;//new Blob([img.src],{type: imgfile.type})
                if(option.value == 'identify'){
                    shader.setAttribute('class', 'header-shade-alive');
                    canvas.showimg(img, function (canvas) {
                        var header = canvas.getHeaderImage(shader.offsetLeft, shader.offsetTop, shader.offsetWidth, shader.offsetHeight);
                        extractImage(header);
                    });
                }else{
                    canvas.showimg(img);
                    extractImage(img.src);
                }
			};
			img.onerror = function (e) {
				alert("图片类型不正确!");
			};
		};
		reader.readAsDataURL(imgfile);

	}, false);

	return localimage;
}

function extractImage(img){
    // upload_data.image = img;//new Blob([img],{type: upload_data.image_type});
    var data = img.split(',')[1];
    data = window.atob(data);

    var buffer = new ArrayBuffer(data.length),
        ubuffer = new Uint8Array(buffer);
    for(var i=0;i<data.length;i++)
        ubuffer[i] = data.charCodeAt(i);
    upload_data.image = new Blob([ubuffer],{type: upload_data.image_type});
}


function getOnevh(n) {
	// 获取当前屏幕1vh的像素大小
	n = n == undefined ? 1 : n;
	return window.innerHeight / 100 * n;
}

function getOnevw(n) {
	// 获取当前屏幕1vw的像素大小
	n = n == undefined ? 1 : n;
	return window.innerWidth / 100 * n;
}


/**
 * Ajax 封装
 * @param {String} url 请求URL
 * @param {String} method 指定Http请求方法
 * @param {Object} param 请求参数
 * @param {Boolean} sync 是否异步
 * @param {Object} option 可选参数
 * @param {Function} success 成功的回调函数
 * @param {Function} error 失败的回调函数
 */
function ajax(url, method, param, sync, option, success, error) {
	if (!sync) sync = false;
	var xhl, newparam = [];
	if (window.XMLHttpRequest) {
		xhl = new XMLHttpRequest();
		xhl.onreadystatechange = function (e) {
			if (xhl.readyState == 4 && xhl.status == 200) {
				// TO DO
				if (success && typeof success == 'function')
					success(e);
			} else if (xhl.readyState == 3 || xhl.readyState == 4) {
				if (error && typeof error == 'function')
					error(e);
			}
		}
	} else {
		alert("[QAQ] 你的破壁浏览器不支持Ajax，赶紧卸载了吧!!")
	}

	if (param) {
		if (method.toLowerCase() == 'get') {
			for (var key in param)
				newparam.push(key + '=' + param[key]);
			param = newparam.join('&')
			url = url + '?' + param
		} else {
			var form = new FormData();
			for (var key in param)
				form.append(key, param[key]);
			param = form
		}
	}
	xhl.open(method, url, sync)
	if (option)
		for (var key in option)
			xhl.setRequestHeader(key, option[key]);
	if (method.toLowerCase() == 'get')
		xhl.send();
	else
		xhl.send(param);
}